package com.cmccgz.udacs_landlord_webapp.main.host;


import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.base.PermissionUtils;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.adapter.HostMenuAdapter;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.DeviceInfoBean;
import com.cmccgz.udacs_landlord_webapp.bean.HostMenuBean;
import com.cmccgz.udacs_landlord_webapp.bean.PushRequestBean;
import com.cmccgz.udacs_landlord_webapp.bean.WebBean;
import com.cmccgz.udacs_landlord_webapp.interfaces.OnRvItemClickListenter;
import com.cmccgz.udacs_landlord_webapp.jpush.AccreditListActivity;
import com.cmccgz.udacs_landlord_webapp.main.user.userinfo.UserInfoActivity;
import com.cmccgz.udacs_landlord_webapp.update.CheckUpdate;
import com.cmccgz.udacs_landlord_webapp.utils.BluetoothOpenDoorUtil;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.cmccgz.udacs_landlord_webapp.utils.BluetoothOpenDoorUtil.REQUEST_ENABLE_BT;

/**
 * @author INX
 *         房东端客户端
 */
public class HostActivity extends BaseActivity implements HostContract.View, View.OnClickListener, OnRvItemClickListenter {
    private HostContract.Presenter presenter;
    private List<HostMenuBean> datas = new ArrayList<>();
    private RecyclerView rv_menu;
    private HostMenuAdapter adapter;
    private ViewHelper mViewHelper;
    private View v_left, v_right;
    public static final String CLOSE_HOST = "close_host";
    private static final int LOCATION_PERMISSION_ASK = 0x77;
    private boolean isBluetoothEnable;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish(false);
        }
    };
    private List<DeviceInfoBean> fastDatas = new ArrayList<>();
    private List<WebBean> bannerDatas = new ArrayList<>();
    private List<PushRequestBean> pushRequestDatas=new ArrayList<>();
    private static final int REQ_ACCREDITE_LIST=101;

    private PermissionUtils.PermissionAskCallback permissionCallback = new PermissionUtils.PermissionAskCallback() {
        @Override
        public void hasPermissionDoNext() {
            checkBlueTooth();
        }
    };


    @Override
    protected int setLayoutId() {
        return R.layout.activity_host;
    }

    @Override
    protected void initView() {
        rv_menu = ((RecyclerView) findViewById(R.id.rv_menu));
        adapter = new HostMenuAdapter(mContext, datas, fastDatas, bannerDatas,this);
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemViewType(position) != HostMenuAdapter.TYPE_MENU) {
                    return 3;
                }
                return 1;
            }
        });
        rv_menu.setLayoutManager(layoutManager);
        rv_menu.setAdapter(adapter);
//        rv_menu.addItemDecoration(new DividerGridItemDecoration(mContext));
        v_left = findViewById(R.id.v_left);
        v_right = findViewById(R.id.v_right);
        v_left.setOnClickListener(this);
        v_right.setOnClickListener(this);
        new HostPresenter(this);
        //初始化列表数据
        presenter.initData(this);
        registerReceiver(mReceiver, new IntentFilter(CLOSE_HOST));
//        syncDevice();
        initBluetooth();
        presenter.getReqList("","","1");

        checkUpdate();
    }

    private void initBluetooth() {
        int state = BluetoothOpenDoorUtil.checkBlueEnable(this);
        switch (state) {
            case BluetoothOpenDoorUtil.STATE_BLUETOOTH_LE_FEATURE_UNABLE:
            case BluetoothOpenDoorUtil.STATE_BLUETOOTH_UNABLE:
                isBluetoothEnable = false;
                break;
            case BluetoothOpenDoorUtil.STATE_BLUETOOTH_ENABLE:
                isBluetoothEnable = true;
                break;
            default:
                isBluetoothEnable = false;
                break;
        }
    }

    private void syncDevice() {
        Intent intent = new Intent(mContext, SyncDeviceIntentService.class);
        mContext.startService(intent);
    }

    public void checkUpdate() {
        // 检查更新
        CheckUpdate.getInstance().start(HostActivity.this, false);
    }

    @Override
    protected void initFragment() {

    }

    @Override
    protected void beforePermission() {
        mViewHelper = ViewHelper.instance(mContext);
        if (mViewHelper != null) {
            mViewHelper.setTitle("首页");
            mViewHelper.setAllVisable(false);
            mViewHelper.setImageRightVisable(true);
            mViewHelper.setImageLeftVisable(true);
            mViewHelper.setPointLeftVisable(false);
            mViewHelper.setImageRight(R.mipmap.icon_setup);
            mViewHelper.setImageLeft(R.drawable.ic_msg);
        }
    }

    @Override
    protected int setSystemBarColorId() {
        return 0;
    }

    @Override
    public void getdata(List<HostMenuBean> datas, List<DeviceInfoBean> fastDatas, List<WebBean> bannerDatas) {
        if (datas == null) {
            datas = new ArrayList<>();
        }
        this.datas.clear();
        this.datas.addAll(datas);

        if (bannerDatas == null) {
            bannerDatas = new ArrayList<>();
        }
        this.bannerDatas.clear();
        this.bannerDatas.addAll(bannerDatas);

        updateFastDatas(fastDatas);
        adapter.notifyDataSetChanged();
    }

    public void updateFastDatas(List<DeviceInfoBean> fastDatas) {
        if (fastDatas == null) {
            fastDatas = new ArrayList<>();
        }else if (fastDatas.size()>2){
            List<DeviceInfoBean> newfastDatas=new ArrayList<>();
            newfastDatas.add(fastDatas.get(0));
            newfastDatas.add(fastDatas.get(1));
            fastDatas=newfastDatas;
        }
        this.fastDatas.clear();
        this.fastDatas.addAll(fastDatas);
    }

    @Override
    public void dismissLoadingDialog() {
        super.dismissLoadingDialog();
    }

    @Override
    public void getDevicesCache(List<DeviceInfoBean> data) {
        final List<String> deviceIds = new ArrayList<>();
        final String[] nameArray = new String[data.size()];
        for (int i = 0; i < data.size(); i++) {
            deviceIds.add(i, data.get(i).device_id);
            nameArray[i] = TextUtils.isEmpty(data.get(i).house_name) ? "" : data.get(i).house_name;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择门禁");
        builder.setItems(nameArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("第" + which + "个");
                String name = nameArray[which];
                final String deviceId = deviceIds.get(which);
                openDoor(name, deviceId);
            }
        });
        builder.show();

        updateFastDatas(data);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void getDevicesSuccess(List<DeviceInfoBean> data) {
        updateFastDatas(data);
        adapter.notifyDataSetChanged();
    }

    public void openDoor(String name, final String deviceId) {
        showConfirmDialog("提示", "确定解锁‘" + name + "’吗？", "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showLoadingDialog("正在远程开锁...");
                presenter.openDoor(AppConfig.getMobile(mContext), deviceId);
            }
        }, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void showErrorMsg(String errorMsg) {
        ToastUtils.show(mContext, errorMsg);
    }

    @Override
    public void getReqListSuccess(List<PushRequestBean> datas, boolean isNoAccredited) {
        pushRequestDatas.clear();
        if (datas!=null) {
            pushRequestDatas.addAll(datas);
        }
        Log.e("inx", "getReqListSuccess: isNoAccredited="+isNoAccredited);
        mViewHelper.setPointLeftVisable(isNoAccredited);
    }

    @Override
    public void getReqListError(String msg) {

    }

    @Override
    public void openDoorSuccess() {
        ToastUtils.show(mContext, "成功开门");
    }

    @Override
    public void setPresenter(HostContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.v_left:
                //蓝牙解锁
//                intent = new Intent(mContext, BtUnlockActivity.class);
                if (isBluetoothEnable) {
                    PermissionUtils.askPermission(this, LOCATION_PERMISSION_ASK, permissionCallback, Manifest.permission.ACCESS_COARSE_LOCATION);
                } else {
                    showToast("蓝牙不可用！");
                }
                break;
            case R.id.v_right:
                //远程解锁
                presenter.getDevices();
                break;
            case R.id.iv_right:
                intent = new Intent(mContext, UserInfoActivity.class);
                break;
            case R.id.iv_left:
                intent=new Intent(mContext, AccreditListActivity.class);
                intent.putExtra(AccreditListActivity.KEY_CACHE_DATAS, (Serializable) pushRequestDatas);
                startActivityForResult(intent,REQ_ACCREDITE_LIST);
                return;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private void checkBlueTooth() {
        boolean isEnableBluetooth = BluetoothOpenDoorUtil.checkBlueTooth(this);
        if (isEnableBluetooth) {
            bluetoothOpenDoor();
        } else {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE_BT);
        }
    }

    private void bluetoothOpenDoor() {
        final List<DeviceInfoBean> list = AppConfig.getDeviceList();
        final String[] nameArray = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            nameArray[i] = TextUtils.isEmpty(list.get(i).house_name) ? "" : list.get(i).house_name;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择门禁");
        builder.setItems(nameArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = nameArray[which];
                final DeviceInfoBean deviceBean = list.get(which);
                showConfirmDialog("提示", "确定解锁‘" + name + "’吗？", "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        showUnCancelLoadingDialog("正在蓝牙开锁...");
                        bluetoothDoOpenDoor(deviceBean.device_name, deviceBean.sn, deviceBean.psd);
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }
        });
        builder.show();

    }

    private void bluetoothDoOpenDoor(String device_name, String sn, String psd) {
        BluetoothOpenDoorUtil.unlockDoor(mContext, device_name, sn, psd, new BluetoothOpenDoorUtil.openDoorCallback() {
            @Override
            public void onSuccess() {
                showToast("开门成功");
            }

            @Override
            public void onFailed(String msg) {
                showToast(msg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        BluetoothOpenDoorUtil.clear();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
                    bluetoothOpenDoor();
                } else {
                    showToast("请打开蓝牙！");
                }
                break;
            case REQ_ACCREDITE_LIST:
                if (resultCode != Activity.RESULT_OK)
                    return;
                boolean isNoAccredited =data!=null&&data.getBooleanExtra(AccreditListActivity.KEY_NO_ACCREDITED, false);
                mViewHelper.setPointLeftVisable(isNoAccredited);
                Log.e("inx", "onActivityResult: isNoAccredited="+isNoAccredited);
                break;
        }
       /* boolean isOpen = (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK);
        if (isOpen) {
            bluetoothOpenDoor();
        } else {
            showToast("请打开蓝牙！");
        }*/
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_ASK) {
            PermissionUtils.handlePermissionRequest(permissions, grantResults, this, permissionCallback, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    }

    @Override
    public void onItemClick(Object o, int position, View itemView) {
//        presenter.openDoor(AppConfig.getMobile(mContext));
        switch (adapter.getItemViewType(position)) {
            case HostMenuAdapter.TYPE_LABEL_FAST:
                v_right.performClick();
                break;
            case HostMenuAdapter.TYPE_FAST:
                DeviceInfoBean deviceByPositioin = adapter.getDeviceByPositioin(position);
                openDoor(deviceByPositioin.house_name,deviceByPositioin.device_id);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter!=null&&adapter.getBanner()!=null) {
            adapter.getBanner().startAutoPlay();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (adapter!=null&&adapter.getBanner()!=null) {
            adapter.getBanner().stopAutoPlay();
        }
    }
}
